package org.example.helloworld;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Scanner;

/**
 * 简单的入门
 * P -> QUEUE -> C
 */
public class HelloWordProducerTest {
    //消息队列名称
    private final static String QUEUE_NAME = "hello";


    public static void main(String[] args) throws Exception {

        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();

        //2.设置公布过程连接的主机ip
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setConnectionTimeout(10000);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        try (Connection connection = connectionFactory.newConnection()) {
            //3.获取channel对象
            Channel channel = connection.createChannel();
            //4.声明一个队列
            // To send, we must declare a queue for us to send to; then we can publish a message to the queue,
            // all of this in the try-with-resources statement:
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String line = scanner.next();
                channel.queueDeclare(QUEUE_NAME, false, false, false,
                        new HashMap<String, Object>());
                //5.发送消息
                channel.basicPublish("", QUEUE_NAME, null, line.getBytes());
                System.out.println(" [x] Sent '" + line + "'");
                if (line.equals("exit")) {
                    System.exit(1);
                }
            }

        } finally {
            //do nothing

        }
    }
}
